package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 后台订单信息分页查询
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, @DateTimeFormat String beginTime, @DateTimeFormat String endTime) {
        log.info("分页查询" + page + "  :  " + pageSize);
        log.info("分页查询" + beginTime + "  :  " + endTime);
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
       /* //处理时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //要判断传过来的时间是否为空
        Date begin = null;
        Date end = null;
        try {
            if (beginTime != null) {
                begin = sdf.parse(beginTime);
            }
            if (endTime != null) {
                end = sdf.parse(endTime);
            }*/

        //设置时间条件
        lqw.between(beginTime != null, Orders::getOrderTime, beginTime, endTime);
        lqw.orderByDesc(Orders::getCheckoutTime);

        //设置订单号条件
        lqw.eq(number != null, Orders::getNumber, number);

        //查询
        orderService.page(pageInfo, lqw);

        return R.success(pageInfo);
    }

    /**
     * 后台修改订单状态
     *
     * @return
     */
    @PutMapping
    public R<String> put(@RequestBody Orders orders) {
        log.info("orders:{}", orders);
        //根据顶到找到数据库对应的orders
        Orders ordersbyId = orderService.getById(orders.getId());
        ordersbyId.setStatus(orders.getStatus()); //修改状态
        orderService.updateById(ordersbyId);
        return R.success("修改成功");
    }

    /**
     * 前台页面订单分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("userPage")
    public R<Page> userPage(int page, int pageSize) {
        log.info("user分页查询" + page + "  :  " + pageSize);

        //构造分页构造器
        Page<Orders> pageInf = new Page(page, pageSize);
        Page<OrdersDto> dtoPage = new Page();

        //获取当前用户id
        Long userId = BaseContext.getCurrentId();

        //先基础查询
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, userId);
        lqw.orderByDesc(Orders::getCheckoutTime);

        orderService.page(pageInf, lqw);
        //把继承的基础信息的分页数据拷贝过去
        BeanUtils.copyProperties(pageInf, dtoPage, "records");
        //获取原分页中的套餐数据集合
        List<Orders> records = pageInf.getRecords();  //这里的集合其实就是根据UserId找到的orders集合
        //对集合属性操作
        List<OrdersDto> dtoList = records.stream().map((item) -> { //item:每个order对象
            //创建一个第三方类
            OrdersDto ordersDto = new OrdersDto();
            //拷贝基本信息
            BeanUtils.copyProperties(item, ordersDto);
            //根据Id获取对应的Orders订单信息
            Orders order = orderService.getById(item.getId());//这里问题大

            //拷贝orderDetails
            Long id = order.getId();
            LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper();
            lqw2.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> list = orderDetailService.list(lqw2);
            ordersDto.setOrderDetails(list);

            //返回第三方复合类Dto
            return ordersDto;
        }).collect(Collectors.toList());

        //分页构造器设置
        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
    }

    /**
     * 前台用户下单
     * Request URL: http://localhost:8080/order/submit
     * Request Method: POST
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 再来一单
     *
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        //获取前端传递的id
        Long ordersId = orders.getId();
        //根据ordersId 查询 订单详情
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ordersId != null, OrderDetail::getOrderId, ordersId);
        //一个订单 对应了多个订单详情 每一个菜对应一条数据
        List<OrderDetail> orderDetails = orderDetailService.list(lqw);

        //因为再来一单是直接跳转首页购物车，所以添加购物车之前 先清空
        shoppingCartService.clean();
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = orderDetails.stream().map((item) -> {

            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                //如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            } else {
                //添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
        return R.success("添加成功");
    }
}


